package edu.towson.cis.cosc490.lab6;

import android.app.ListActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ToDoListActivity extends ListActivity implements OnClickListener{
    
	private Button m_addButton;
	@SuppressWarnings("unused")
	private ListView m_itemListView;
	private ToDoItemsData m_dbListData;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        m_dbListData = new ToDoItemsData(this);
        
        initLayout();
        
        // register the context menu to delete/send SMS
        registerForContextMenu(getListView());
        
        showToDoItems();
    }
    
    // Show the to-do items in the ListView using an adapter
    private void showToDoItems(){
    	
		// connect to database and query
        Cursor cursor = getToDoItems();
        
		// Using the adapter to set a ListView
    	String[] FROM = {Constants._ID, Constants.PRIORITY, Constants.ITEM};
    	int[] TO = {R.id.rowid, R.id.priority, R.id.item};
    	SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.list_item, cursor, FROM, TO);
		setListAdapter(sca);
    }
    
    // Query the database and return a Cursor of to-do items.
    private Cursor getToDoItems(){
    	SQLiteDatabase db = m_dbListData.getReadableDatabase();
		Cursor cursor = db.query(Constants.TABLE_NAME, null, null, null, null, null, Constants.TIME +" DESC", null);
		startManagingCursor(cursor);
		return cursor;
    }
    
    // Insert a to-do item into the database
    // TODO: Get a database instance and insert the priority and item information
    // TODO: Add a timestamp when the item was added using System.currentTimeMillis()
    // TODO: Update the ListView
    private void addToDoItem(ToDoItem newItem) {
    	SQLiteDatabase db = m_dbListData.getWritableDatabase();
    	ContentValues values = new ContentValues();
    	values.put(Constants.PRIORITY, newItem.getPriority());
    	values.put(Constants.ITEM, newItem.getToDoItem());
    	values.put(Constants.TIME, System.currentTimeMillis());
    	db.insertOrThrow(Constants.TABLE_NAME, null, values);
    	showToDoItems();
	}
    
	// Called when a TextView item is long-clicked
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	menu.setHeaderTitle("Select an action");
    	menu.add(0, v.getId(), 0, "Send SMS");
    	menu.add(1, v.getId(), 1, "Delete Item");
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	
    	// Get the database _ID of the item that was deleted
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	View listItemView = info.targetView;
    	
    	TextView rowid = (TextView)listItemView.findViewById(R.id.rowid);
    	TextView priority = (TextView)listItemView.findViewById(R.id.priority);
    	TextView description = (TextView)listItemView.findViewById(R.id.item);
    	
    	String id = rowid.getText().toString();
    	String message = priority.getText().toString() + ": " + description.getText().toString();
    	
    	if(item.getTitle() == "Send SMS")
        	sendSMS(message);
        else if(item.getTitle() == "Delete Item")
        	deleteToDoItem(id);
        else
        	return false;
        return true;
    }
    
    // Passes in the _id primary key String of the to-do item to delete
    // TODO: Get a database instance and delete the item with the passed in primary key
    // TODO: Update the ListView
    private void deleteToDoItem(String itemId) {
    	SQLiteDatabase db = m_dbListData.getWritableDatabase();
    	db.delete(Constants.TABLE_NAME, "_ID = " + itemId, null);
    	finish();
    	showToDoItems();
	}

	protected void initLayout(){
    	m_addButton = (Button) this.findViewById(R.id.button1);
    	m_addButton.setOnClickListener(this);
        m_itemListView = getListView();
    }
    
    public void onClick(View v){
    	Intent myIntent = new Intent(this, ToDoItemDetailsActivity.class);
    	this.startActivityForResult(myIntent, 1);
    }
    
	private void sendSMS(String message) {
	    Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.putExtra("sms_body", message);
        smsIntent.putExtra("address", "");
        smsIntent.setType("vnd.android-dir/mms-sms");
        startActivity(smsIntent);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK){
			ToDoItem newItem = new ToDoItem();
			newItem.setToDoItem(data.getExtras().getString("newItem"));
			newItem.setPriority(data.getExtras().getString("priority"));
			addToDoItem(newItem);
		}
	}
}